﻿using Framework.Data;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
using YPD.Common.Model;

namespace Paul.Common.HttpServer
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    [JavascriptCallbackBehavior(UrlParameterName = "callback")]
    [ServiceContract]
    public class Basic
    {
        [WebInvoke(UriTemplate = "Simple", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        //  [WebGet(UriTemplate = "Test/{str}", ResponseFormat = WebMessageFormat.Json)]
        public ReturnPakect<string> Simple(int ipt, int opt, string fileName, string nodeName, params string[] str)
        {

            var rst = new ReturnPakect<string>();
            try
            {
                var dt = GetTable(ipt, opt, fileName, nodeName,str);
                var jsonStr = GetSimpleString(dt, opt);
                rst.SetSuccess(jsonStr);
            }
            catch (Exception ex)
            {
                rst.SetError(ex.Message);
            }

            return rst;


            //if (dt == null || dt.Rows.Count < 1)
            //{
            //    throw new Exception("系统错误");
            //}

            //dynamic obj = new ExpandoObject();

            //if (opt == 1)
            //    obj = dt.Rows[0][0].ToString();
            //else
            //{
            //    obj = new ArrayList();// new string[O];

            //    for (int i = 1; i <= opt; i++)
            //    {
            //        obj.Add(dt.Rows[0][i - 1].ToString());
            //      // obj[i - 1] = dt.Rows[0][i - 1].ToString();
            //    }
            //}

            //var rst = new ReturnPakect<string>();
            //rst.SetSuccess(JsonConvert.SerializeObject(obj));
            //return rst;
        }

        [WebInvoke(UriTemplate = "List", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public ReturnPakect<string> List(int ipt, int opt, string fileName, string nodeName, params string[] str)
        {
            var rst = new ReturnPakect<string>();
            try
            {
                var dt = GetTable(ipt, opt, fileName, nodeName,str);
                var jsonStr = GetTableString(dt, opt);
                rst.SetSuccess(jsonStr);
            }
            catch (Exception ex)
            {
                rst.SetError(ex.Message);
            }

            return rst;
          
        }

        [WebInvoke(UriTemplate = "Page", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public ReturnPakect<PagerData<ArrayList>> Page(int ipt, int opt, string fileName, string nodeName, params string[] str)
        {
            var rst = new ReturnPakect<PagerData<ArrayList>>();
            try
            {
                var dt = GetTable(ipt, opt, fileName, nodeName, str);
                rst.SetSuccess(GetPageObj(dt, opt,int.Parse(str[0]), int.Parse(str[1])));
               
            }
            catch (Exception ex)
            {
                rst.SetError(ex.Message);
            }

            return rst;

        }

        public DataTable GetTable(int ipt, int opt, string fileName, string nodeName, params string[] str)
        {
            var dm = new DataManager(fileName, nodeName);
            for (var i = 1; i <= ipt; i++)
            {
                dm.SetParameters($"param{i}", str[i - 1]);
            }
            dm.SetParameters("error", "");
            var dt = dm.ExecuteDataTable();
            var error = "";
            if (dm.GetParameters("error") != null)
                error = dm.GetParameters("error").ToString();
            if (error.Length > 0)
                throw new Exception(error);
            return dt;
        }

        public string GetSimpleString(DataTable dt, int opt)
        {
          

            dynamic obj = new ExpandoObject();

            if (dt == null || dt.Rows.Count < 1)
            {
                if (opt == 1)
                    obj = "";
                else
                {
                    obj = new ArrayList();// new string[O];

                    for (int i = 1; i <= opt; i++)
                    {
                        obj.Add("");
                        // obj[i - 1] = dt.Rows[0][i - 1].ToString();
                    }
                }

            }
            else
            {
                if (opt == 1)
                    obj = dt.Rows[0][0].ToString();
                else
                {
                    obj = new ArrayList();// new string[O];

                    for (int i = 1; i <= opt; i++)
                    {
                        obj.Add(dt.Rows[0][i - 1].ToString());
                        // obj[i - 1] = dt.Rows[0][i - 1].ToString();
                    }
                }

            }


            return JsonConvert.SerializeObject(obj);

        }

        public string GetTableString(DataTable dt, int opt)
        {
            //if (dt == null || dt.Rows.Count < 1)
            //{
            //    throw new Exception("系统错误");
            //}

            dynamic obj = new ExpandoObject();




            obj = new ArrayList();
            var tmp = new ArrayList();
          
            foreach (DataRow row in dt.Rows)
            {

                tmp = new ArrayList();
                for (int i = 1; i <= opt; i++)
                {
                    tmp.Add(row[i-1].ToString());
                }
                obj.Add(tmp);
              
            }

            return JsonConvert.SerializeObject(obj);
        }

        public PagerData<ArrayList> GetPageObj(DataTable dt, int opt,int ind,int topN)
        {
           
            var pagerRst = new PagerData<ArrayList>();
            pagerRst.PageIndex = ind;
            pagerRst.PageSize = topN;
            pagerRst.RowCount = 0;
            pagerRst.PageCount = 0;
            pagerRst.PageData = new List<ArrayList>();
            if (dt == null || dt.Rows.Count == 0)
                pagerRst.PageData = null;
            else {
                pagerRst.RowCount = int.Parse(dt.Rows[0][0].ToString());
               
            }

            var tmp = new ArrayList();

            foreach (DataRow row in dt.Rows)
            {

                tmp = new ArrayList();
                for (int i = 1; i <= opt; i++)
                {
                    tmp.Add(row[i].ToString());
                }
                pagerRst.PageData.Add(tmp);        

            }

            pagerRst.PageCount = pagerRst.RowCount % pagerRst.PageSize > 0 ? ((pagerRst.RowCount / pagerRst.PageSize) + 1) : (pagerRst.RowCount / pagerRst.PageSize);
            return pagerRst;
           // return JsonConvert.SerializeObject(pagerRst);
        }
    }
}
